<template>
  <div>
    <el-card class="top"><el-header>商品列表</el-header></el-card>

    <!-- 表格展示 -->
    <el-card>
      <el-input placeholder="商品名称" prefix-icon="el-icon-search" style="width: 200px" v-model="name">
      </el-input>
      <el-button type="warning" @click="reload" plain>查询</el-button>

      <el-button type="warning" @click="addformVisible = true" v-if="canEditAndDelete">新增商品</el-button>
      <span>你的可用积分：{{ this.points }}</span>
      <el-table :data="goodsList" style="width: 100%" :sort-by.sync="sortKey"
        :sort-orders="['ascending', 'descending']">
        <el-table-column type="index" label="编号" width="50" align="center">
        </el-table-column>
        <el-table-column prop="name" label="商品名称" width="150" align="center">
        </el-table-column>
        <el-table-column prop="type" label="商品类型" width="150" align="center">
        </el-table-column>
        <el-table-column prop="money" label="积分价格" width="150" align="center" sortable>
        </el-table-column>
        <el-table-column prop="num" label="商品库存" width="100" align="center" sortable>
        </el-table-column>
        <el-table-column prop="volume" label="商品销量" width="100" align="center" sortable>
        </el-table-column>
        <el-table-column prop="state" label="商品状态" width="150" align="center" sortable>
          <template slot-scope="scope">
            <span v-if="scope.row.state == 0">已下架</span>
            <span v-if="scope.row.state == 1">可兑换</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300">
          <template slot-scope="scope">
            <!-- v-if="canEditAndDelete"  v-else-->
            <el-button v-if="canEditAndDelete" size="mini" type="primary"
              @click="editformVisible = true, handleEdit(scope.row)">编辑</el-button>
            <el-button v-if="canEditAndDelete" size="mini" type="danger" @click="del(scope.row.id)">删除</el-button>
            <el-button size="mini" type="danger" @click="buyformVisible = true, handleBuy(scope.row)">兑换</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 购买 -->
    <el-dialog title="商品确定信息" :visible.sync="buyformVisible" :modal-append-to-body="false">
      <el-form :model="buyform">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="username" autocomplete="off" :disabled="true">
          </el-input>
        </el-form-item>
        <el-form-item label="联系方式" :label-width="formLabelWidth">
          <el-input v-model="phone" autocomplete="off" :disabled="true">
          </el-input>
        </el-form-item>
        <el-form-item label="商品名称" :label-width="formLabelWidth">
          <el-input v-model="buyform.name" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="商品类型" :label-width="formLabelWidth">
          <el-input v-model="buyform.type" autocomplete="off" :disabled="true">
          </el-input>
        </el-form-item>
        <el-form-item label="积分价格" :label-width="formLabelWidth">
          <el-input v-model="money" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="可用积分" :label-width="formLabelWidth">
          <el-input v-model="points" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="总兑换价格" :label-width="formLabelWidth">
          <el-input v-model="totalCost" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="兑换数量" :label-width="formLabelWidth">
          <el-input-number v-model="buyform.num" @change="handleChange" :min="1" :max="10"></el-input-number>
        </el-form-item>
        <el-form-item label="收获地址" :label-width="formLabelWidth">
          <el-input v-model="buyform.address" autocomplete="off">
          </el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="buyformVisible = false">取 消</el-button>
        <el-button type="primary" @click="buy()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新增 -->
    <el-dialog title="新增商品信息" :visible.sync="addformVisible" :modal-append-to-body="false">
      <el-form :model="addform">
        <el-form-item label="商品名称" :label-width="formLabelWidth">
          <el-input v-model="addform.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品类型" :label-width="formLabelWidth">
          <el-input v-model="addform.type" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="兑换积分" :label-width="formLabelWidth">
          <el-input v-model="addform.money" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" :label-width="formLabelWidth">
          <el-input v-model="addform.num" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addformVisible = false">取 消</el-button>
        <el-button type="primary" @click="add()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog title="编辑商品信息" :visible.sync="editformVisible" :modal-append-to-body="false">
      <el-form :model="editform">
        <el-form-item label="商品名称" :label-width="formLabelWidth">
          <el-input v-model="editform.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品类型" :label-width="formLabelWidth">
          <el-input v-model="editform.type" autocomplete="off">
          </el-input>
        </el-form-item>
        <el-form-item label="兑换积分" :label-width="formLabelWidth">
          <el-input v-model="editform.money" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品库存" :label-width="formLabelWidth">
          <el-input v-model="editform.num" autocomplete="off"></el-input>
        </el-form-item>
        <template>
          <el-radio v-model="editform.state" label="1">上架商品</el-radio>
          <el-radio v-model="editform.state" label="0">下架商品</el-radio>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editformVisible = false">取 消</el-button>
        <el-button type="primary" @click="edit()">确 定</el-button>
      </div>
    </el-dialog>

    <!--    分页-->
    <el-row>
      <el-col style="text-align:right">
        <el-pagination :current-page="currentPage" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :page-size="pageSize" :page-sizes="[5, 10, 15]" layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-col>
    </el-row>
  </div>

</template>

<script>
import { del } from 'vue';

export default {
  data() {
    return {
      money: '',
      goodsState: '',
      allnum: '',
      username: '',
      phone: '',
      address: '',
      sortKey: '',
      points: {},
      uid: "",
      rolename: '',
      name: "",
      goodsList: [],
      addformVisible: false,
      editformVisible: false,
      buyformVisible: false,
      addform: {},
      buyform: {
        uid: '',
        gid: '',
        money: '',
        phone: '',
        num: '',
        totalCost: '',
        address: '',
        state: '',
      },
      editform: {
        name: '',
        type: '',
        money: '',
        num: '',
        state: '',
      },
      formLabelWidth: '120px',
      //配置分页
      currentPage: 1,
      pageSize: 5,
      total: 0
    };
  },

  created() {
    const storedUserInfo = localStorage.getItem('user');
    if (storedUserInfo) {
      this.user = JSON.parse(storedUserInfo);
      console.log(this.user.uid);
      this.uid = this.user.uid;
      this.rolename = this.user.roleList[0].name;
      this.phone = this.user.phone;
      this.username = this.user.name;
      console.log(this.rolename);
    }
  },

  computed: {
    // 计算总价格
    totalCost() {
      this.buyform.totalCost = this.money * this.buyform.num
      return this.money * this.buyform.num;
    },

    // 根据用户角色决定是否显示编辑和删除按钮
    canEditAndDelete() {
      //return this.rolename === 'admin';
      const rolenames = ['超级管理员', '产品经理', '后台管理员', '客服经理'];
      return rolenames.includes(this.rolename); // 只有指定角色可以编辑和删除
    }
  },

  mounted() {

    this.reload();

    this.getpoints();
  },

  methods: {
    //添加
    add() {
      this.$axios.post("/goods/add", this.addform).then(res => {
        console.log(res);
        if (res.data.code == 200) {
          //对话框消失
          this.addformVisible = false;
          //清空新增留存上一个数据
          this.addform = {};
          //给出添加成功或者失败提示
          this.$message({
            message: "添加成功",
            type: 'success'
          });
          this.reload();
        } else {
          this.addformVisible = false
          this.$message({
            message: "添加失败",
            type: 'error'
          });
        }
      })
    },

    // 编辑
    edit(row) {
      this.editformVisible = true
      Object.assign(this.editform, row)
      this.$axios.put("/goods/edit", this.editform).then(res => {
        if (res.data.code == 200) {
          this.$message({
            message: "编辑成功",
            type: 'success'
          });
          this.editformVisible = false
        } else {
          this.$message.console.error("编辑失败");
        }
        this.reload();
      })
    },

    // 购买
    buy() {
      if (this.allnum <= this.paynum) {
        this.$message({
          message: "商品库存不足，请重新选择商品兑换",
          type: 'error'
        });
        this.buyformVisible = false
      } else if (this.goodsState == 0) {
        this.$message({
          message: "商品已被下架，请重新选择商品兑换",
          type: 'error'
        });
        this.buyformVisible = false
      } else if (this.points < this.money) {
        this.$message({
          message: "积分不足，请充值",
          type: 'error'
        });
        this.buyformVisible = false
      } else {
        console.log(this.buyform);
        this.$axios.post("/goods/buyGoods", this.buyform).then(res => {
          console.log(res.data);
          if (res.data.code == 200) {
            this.$message({
              message: "兑换成功",
              type: 'success'
            });
            this.buyformVisible = false
          } else {
            this.$message.console.error("兑换失败");
          }
          this.reload();
          this.getpoints();

        })
      }
    },

    // 删除
    del(id) {
      this.$axios.delete("/goods/delete/" + id).then(res => {
        if (res.data.code == 200) {
          this.$message({
            message: "删除成功",
            type: 'success'
          });
          this.reload();
        } else {
          this.$message.console.error("删除失败");
        }
      })
    },

    //显示查询出的总条数
    reload() {
      this.$axios.get("/goods/findAll?currentPage=" + this.currentPage + "&pageSize=" + this.pageSize + "&name=" + this.name).then((res) => {
        console.log(res.data.data);
        this.goodsList = res.data.data.list;
        this.total = res.data.data.total;
        this.money = res.data.data.list.money;
      });
    },

    // 显示积分
    getpoints() {
      this.$axios.get("/points/findById/" + this.uid).then((res) => {
        console.log(res);
        this.points = res.data.data.points;
      });

    },


    handleEdit(row) {
      this.editform = { ...row };
    },

    handleBuy(row) {
      console.log(row);
      this.allnum = row.num;
      this.money = row.money;
      this.goodsState = row.state;
      this.buyform = { ...row };
      this.buyform.uid = this.uid;
      this.buyform.gid = row.id;
      this.buyform.phone = this.phone;
      this.buyform.money = this.totalCost;
    },

    handleChange(val) {
      this.paynum = val;
      console.log(this.paynum);
    },

    //显示查询出的总条数
    handleSizeChange(val) {
      this.pageSize = val;
      this.reload();
    },

    //点击新页查询的数据
    handleCurrentChange(val) {
      this.currentPage = val;
      this.reload();
    },
  },
};
</script>

<style scoped>
.el-header {
  text-align: center;
  line-height: 30px;
  size: 120px;
}

.top {
  background-color: #D3D3D3;
  height: 60px;
}

.el-card {
  margin-top: 10px;
  margin-left: 30px;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>